package cn.leonis.leetcode;

import java.util.Arrays;

/**
 * @Author Tobi
 * @Date 2022-07-14 下午3:15
 * leetcode 724 寻找数组的中心下标
 */
public class FindPivotIndexSolution {

    public static void main(String[] args) {
        int[] nums = {2, 1, -1};
        FindPivotIndexSolution solution = new FindPivotIndexSolution();
        System.out.println(solution.pivotIndex(nums));
    }

/*    public int pivotIndex(int[] nums) {
// 双指针解法
        int left = 0;
        int right = nums.length - 1;
        int leftSum = 0;
        int rightSum = 0;
        while (left <= right) {

        }
        return -1;
    }*/

    /**
     * 前缀和
     * @param nums
     * @return
     */
    public int pivotIndex(int[] nums) {
        int arraySum = Arrays.stream(nums).sum();
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if (2 * sum + nums[i] == arraySum) {
                return i;
            }
            sum += nums[i];
        }
        return -1;
    }
}
